<template>
  <el-card shadow="always">
    <div slot="header" class="clearfix" style="height: 20px" v-show="ashowflag">
      <span><el-form ref="form"  label-width="80px" >
        <el-form-item label="入住">
          <el-select
            v-model="checkInMark"
            clearable
            filterable
            remote
            :loading="loading"
            placeholder="请输入老人姓名、身份证号或编号"
            :remote-method="searchCheckIn"
            @change="searchAllInfo">
            <el-option style="width: 1000px"
                       v-for="item in checkInList"
                       :disabled="item.checkin.retreat"
                       :key="item.checkin.checkInMark"
                       :label="item.elderlyinfo.elderlyName"
                       :value="item.checkin.checkInMark">
              <el-row :gutter="20">
<!--                <el-col :span="4"><span style="float: left"><el-tag>档案号</el-tag>{{ item.elderlyinfo.elderlyCode }}</span></el-col>-->
                <el-col :span="3"><span style="float: left"><el-tag type="success">姓名</el-tag>{{ item.elderlyinfo.elderlyName }}</span></el-col>
                <el-col :span="5"><span style="float: left"><el-tag>证件号</el-tag>{{ item.elderlyinfo.cardNo }}</span></el-col>
                <el-col :span="4"><span style="float: left"><el-tag type="warning">入住编号</el-tag>{{ item.checkin.checkInMark }}</span></el-col>
                <el-col :span="6"><span style="float: left"><el-tag>入住时间</el-tag>{{ item.checkin.checkedInTime }}</span></el-col>
                <el-col :span="2"><span style="float: left">
                  <el-tag v-if="item.checkin.retreat" type="danger">退住</el-tag>
                  <el-tag v-else>入住</el-tag></span>
                </el-col>
              </el-row>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form></span>
    </div>
    <div class="text item">
      <el-row :gutter="24" v-show="ashowflag">
        <el-col :span="6">
          <span>账户编号：{{accountInfo.accountNumber}}</span>
        </el-col>
        <el-col :span="6">
          <span>入住老人：{{accountInfo.elderlyName}}</span>
        </el-col>
        <el-col :span="6">
            <span>入住状态：<el-tag v-if="accountInfo.retreat" type="info">已退住</el-tag>
              <el-tag v-else type="success">入住中</el-tag>
            </span>
        </el-col>
        <el-col :span="6">
          <span>入住时间：{{accountInfo.checkedInTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</span>
        </el-col>
      </el-row >
      <el-row :gutter="24" v-show="ashowflag">
        <el-col :span="6">
          <span>入住床位：{{accountInfo.checkInBedInfo}}<el-tag v-if="accountInfo.compartment" type="success">包房</el-tag></span>
        </el-col>
        <el-col :span="6">
          <span>预交金：<el-tag type="success">¥</el-tag>{{accountInfo.advancePayment | money}}</span>
        </el-col>
        <el-col :span="6">
          <span>押  金：<el-tag type="success">¥</el-tag>{{accountInfo.deposit | money}}</span>
        </el-col>
      </el-row>
      <el-divider><i class="el-icon-arrow-up" @click="showtop"></i></el-divider>
      <el-row :gutter="24">
        <el-tabs type="border-card" @tab-click="tabClick" value="snapsettle" v-model="name">
          <el-tab-pane name="snapsettle" label="临时收费">
            <el-form :inline="true"  class="demo-form-inline">
              <el-form-item label="收费项目">
                <search-input v-model="snapFee.item" :config="sConfig" @change="selVal1" @clear="itemclear" placeholder="请输入收费项目"></search-input>
                <!-- <el-select
                  v-model="snapFee.item"
                  filterable
                  remote
                  clearable
                  placeholder="请输入收费项目"
                  @change="selVal"
                  @clear="itemclear"
                  :remote-method="searchFeeItem">
                  <el-option style="width: 500px"
                    v-for="item in feeItems"
                    :key="item.mark"
                    :label="item.name"
                    :value="item.mark">
                    <el-row :gutter="20">
                      <el-col :span="6"><span style="float: left"><el-tag>名称</el-tag>{{ item.name }}</span></el-col>
                      <el-col :span="6"><span style="float: left"><el-tag>费用¥</el-tag>{{ item.fee }}</span></el-col>
                      <el-col :span="4"><span style="float: left">
                        <el-tag v-if="item.nurseItemBol" type="success">护理项目</el-tag>
                        <el-tag v-else type="warning" >非护理项目</el-tag></span>
                      </el-col>
                      <el-col :span="4"><span style="float: left">
                        <el-tag v-if="item.charged" type="success">收费</el-tag>
                        <el-tag v-else type="warning" >免费</el-tag></span>
                      </el-col>
                      <el-col :span="4"><span style="float: left">
                        <el-tag v-if="item.change" type="success">可定价</el-tag>
                        </span>
                      </el-col>
                    </el-row>
                  </el-option>
                </el-select> -->
              </el-form-item>
              <el-form-item label="费用">
                <el-input type="number" :disabled="!snapFee.change" v-model.number="snapFee.price" placeholder="费用"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :disabled="!snapFee.item || !accountInfo.checkInMark || accountInfo.retreat" icon="el-icon-plus" circle @click="addfeeitem"></el-button>
              </el-form-item>
              <el-form-item style="float: right">
                <el-button type="primary" :disabled="!snapItem.length>0 || !accountInfo.checkInMark || accountInfo.retreat" @click="writebill">记账</el-button>
              </el-form-item>
              <el-form-item style="float: right">
                <el-button type="primary" :disabled="!snapItem.length>0 || !accountInfo.checkInMark || accountInfo.retreat" @click="writesettle">记账并结算</el-button>
              </el-form-item>
            </el-form>
            <el-table
              :data="snapItem"
              height="400"
              style="width: 100%">
              <el-table-column
                prop="mark"
                label="项目编号"

                min-width="150">
              </el-table-column>
              <el-table-column
                prop="name"
                label="项目名称"
                min-width="150">
              </el-table-column>
              <el-table-column
                prop="nurseItemBol"
                label="项目类型"
                min-width="150">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.nurseItemBol" type="success">护理项目</el-tag>
                  <el-tag v-else type="warning" >非护理项目</el-tag></span>
                </template>
              </el-table-column>
              <el-table-column
                prop="fee"
                label="费用（¥）"
                min-width="150">
                <template slot-scope="scope">
                  <span>{{scope.row.fee | money}}</span>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                label="操作"
                width="120">
                <template slot-scope="scope">
                  <el-button
                    @click.native.prevent="deleteFeeItem(scope.$index, snapItem)"
                    type="text"
                    size="small">
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane name="outedbill" label="已出账单">

            <el-form :inline="true"  class="demo-form-inline">
              <el-form-item label="账单日期">
                <div class="block">
                  <el-date-picker
                    size="mini"
                    value-format="yyyy-MM"
                    v-model="value2"
                    type="month"
                    placeholder="选择月">
                  </el-date-picker>
                </div>
              </el-form-item>
              <el-form-item>

                <el-button type="primary" size="mini" @click="searchOutedBills">查询</el-button>
<!--                <el-button type="warning"  size="mini" @click="generateMonthBill">生成月份账单</el-button>-->

              </el-form-item>
            </el-form>
            <el-table
              :data="outedBills"
              border
              style="width: 100%">
              <el-table-column
                prop="billCode"
                label="账单号"
                min-width="180">
              </el-table-column>
              <el-table-column
                prop="billDate"
                label="账单日期"
                min-width="180">
              </el-table-column>
              <el-table-column
                prop="billFee"
                label="账单金额(¥)"
                min-width="180">
                <template slot-scope="scope">
                  <span>
                    {{scope.row.billFee | money }}
                  </span>
                </template>
              </el-table-column>

              <el-table-column
                prop="settle"
                label="结算状态">
                <template slot-scope="scope">
                  <span>
                    <el-tag type="warning" v-if="scope.row.settle">已结算</el-tag>
                    <el-tag type="info" v-else>未结算</el-tag>
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                label="操作"
                width="100">
                <template slot-scope="scope">
                  <el-button  type="text" size="small" @click="showBillDetail(scope.row)">查看</el-button>
                  <el-button type="text" size="small" v-if="!scope.row.settle && scope.row.billFee>0" @click="settleToBill(scope.row)">结算</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              :current-page="outedbillpage.curr"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="outedbillpage.limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="outedbillpage.total">
            </el-pagination>
          </el-tab-pane>
          <el-tab-pane label="执行费用" name="outingbill">
            <el-form :inline="true"  class="demo-form-inline">
              <el-form-item label="费用类型">
                <el-select v-model="outingbillQuery.feeType"  placeholder="费用类型">
                  <el-option label="全部" value="0"></el-option>
                  <el-option label="未入账" value="1"></el-option>
                  <el-option label="已入账" value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="结算情况">
                <el-select v-model="outingbillQuery.settled"  placeholder="费用类型">
                  <el-option label="全部" value="0"></el-option>
                  <el-option label="未结算" value="1"></el-option>
                  <el-option label="已结算" value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="执行时间" required>
                <el-col :span="11">
                  <el-form-item prop="date1">
                    <el-date-picker type="date" v-model="outingbillQuery.startTime" value-format="yyyy-MM-dd" placeholder="选择日期"  style="width: 100%;"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col class="line" :span="2">-</el-col>
                <el-col :span="11">
                  <el-form-item prop="date2">
                    <el-date-picker type="date" v-model="outingbillQuery.endTime" value-format="yyyy-MM-dd" placeholder="选择日期"  style="width: 100%;"></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-form-item>
              <el-form-item>

                <el-button type="primary" @click="searchOutingBills">查询</el-button>
              </el-form-item>
            </el-form>
            <el-table
              :data="outingBills"
              border
              max-height="400"
              style="width: 100%">
            <el-table-column
              prop="detailNumber"
              fixed
              show-overflow-tooltip
              label="编号"
              min-width="180">
            </el-table-column>
            <el-table-column
              prop="nursingItemName"
              label="费用项目"
              min-width="180">
            </el-table-column>
            <el-table-column
              prop="executionCost"
              label="费用（¥）" min-width="180">
              <template slot-scope="scope">
                <span>{{ scope.row.executionCost | money }}</span>
              </template>
            </el-table-column>
              <el-table-column
                prop="recordedTime"
                label="计费时间"
                min-width="180">
              </el-table-column>
              <el-table-column
                prop="settled"
                label="结算情况"
                min-width="180">
                <template slot-scope="scope">
                  <span>
                    <el-tag type="warning" v-if="scope.row.settled">已结算</el-tag>
                    <el-tag type="info" v-else>未结算</el-tag>
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="billCode"
                label="入账情况"
                min-width="180">
                <template slot-scope="scope">
                  <span>
                    <el-tag type="success" v-if="scope.row.billCode">已入账</el-tag>
                    <el-tag type="info" v-else>未入账</el-tag>
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="revoke"
                label="费用状态"
                min-width="180">
                <template slot-scope="scope">
                  <span>
                    <el-tag type="info" v-if="scope.row.revoke">已撤销</el-tag>
                  </span>
                </template>
              </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="200">
              <template slot-scope="scope">
                <el-button type="text" size="small" v-if="scope.row.settled" v-show="!scope.row.revoke && scope.row.executionCost>0" @click="revokesettledfee(scope.row)">撤销结算</el-button>
                <el-button type="text" size="small" v-show="!scope.row.revoke && scope.row.executionCost>0" @click="revokefee(scope.row.detailNumber)">撤销记账</el-button>
              </template>
            </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="退住结算" name="retreatbill">
            <el-row :gutter="80">
              <el-col :span="12" v-if="retreatCheckInFeeDetail.retreated"><span style="font-size: 20px; color: #ff8866">退住结算已完成</span><br><br>
                <!-- <el-button type="primary" size="mini" @click="depositAdvancePaymentVisible = true" v-if="accountInfo.deposit > 0">退押金</el-button> -->
              </el-col>
              <el-col :span="12" v-if="retreatCheckInFeeDetail.amount && retreatCheckInFeeDetail.amount!=0">

                <span style="margin-right: 10px">退住原因</span>
                <el-select v-model="reason" placeholder="请选择"    size="mini"   @change="requstreason">
                  <el-option

                    v-for="item in settlementReason"
                    :key="item.dcNo"
                    :label="item.name"
                    :value="item.dcNo">
                  </el-option>
                </el-select>

             </el-col>
              <el-col :span="12">
                <el-button type="primary" size="mini" @click="openretreate" v-if="retreatCheckInFeeDetail.amount && retreatCheckInFeeDetail.amount!=0">结算</el-button>
              </el-col>
            </el-row>
            <el-row :gutter="20" v-if="!retreatCheckInFeeDetail.retreated">
              <el-col :span="12">
                <el-card class="box-card">
                  <div slot="header" class="clearfix">
                    <span>未入账费用</span>
                    <span style="float: right"><el-tag>总金额 <span style="color: #001529">{{ retreatCheckInFeeDetail.amount | money }}</span>（¥）</el-tag></span>
                  </div>
                  <el-table v-show="retreatCheckInFeeDetail.noBillFees"
                            :data="retreatCheckInFeeDetail.noBillFees"
                            border
                            style="width: 100%">
                    <el-table-column
                      prop="nursingItemName"
                      label="项目名称"
                      width="180">
                    </el-table-column>
                    <el-table-column
                      prop="executionCost"
                      label="费用（¥）"
                      width="180">
                      <template slot-scope="scope">
                        <span>{{scope.row.executionCost | money}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="产生时间">
                      <template slot-scope="scope">
                        <span v-if="scope.row.recordedTime">{{scope.row.recordedTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</span>

                      </template>
                    </el-table-column>
                  </el-table>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card class="box-card" v-for="(item, key) in retreatCheckInFeeDetail.billFees" :key="key">
                  <div slot="header" class="clearfix">
                    <span>账单号：{{key}}</span>
                  </div>
                  <el-table v-show="item"
                            :data="item"
                            border
                            style="width: 100%">
                    <el-table-column
                      prop="nursingItemName"
                      label="项目名称"
                      width="180">
                    </el-table-column>
                    <el-table-column
                      prop="executionCost"
                      label="费用（¥）"
                      width="180">
                      <template slot-scope="scope">
                        <span>{{scope.row.executionCost | money}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="产生时间">
                      <template slot-scope="scope">
                        <span v-if="scope.row.recordedTime">{{scope.row.recordedTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</span>

                      </template>
                    </el-table-column>
                  </el-table>
                </el-card>
              </el-col>
            </el-row>

          </el-tab-pane>
          <el-tab-pane label="中途结算" name="midwaySettlement">
            <el-row :gutter="80">
              <el-col :span="12" v-if="retreatCheckInFeeDetail.retreated"><span style="font-size: 20px; color: #ff8866">退住结算已完成</span><br><br>
                <!-- <el-button type="primary" size="mini" @click="depositAdvancePaymentVisible = true" v-if="accountInfo.deposit > 0">退押金</el-button> -->
              </el-col>
              <el-col :span="12" v-if="retreatCheckInFeeDetail.amount && retreatCheckInFeeDetail.amount!=0">
<!--                <span style="margin-right: 10px">退住原因</span>-->
<!--                <el-select v-model="reason" placeholder="请选择"    size="mini" >-->
<!--                  <el-option-->

<!--                    v-for="item in settlementReason"-->
<!--                    :key="item.dcNo"-->
<!--                    :label="item.name"-->
<!--                    :value="item.dcNo">-->
<!--                  </el-option>-->
<!--                </el-select>-->
                <span style="float: left"><el-tag>总金额 <span style="color: #001529">{{ retreatCheckInFeeDetail.amount | money }}</span>（¥）</el-tag></span>
              </el-col>
              <el-col :span="12" >
                <el-button type="primary" :disabled="retreatCheckInFeeDetail.amount <= 0" size="mini" @click="openretreate" v-if="retreatCheckInFeeDetail.amount && retreatCheckInFeeDetail.amount!=0">结算</el-button>
              </el-col>
            </el-row>
            <el-row :gutter="20" v-if="!retreatCheckInFeeDetail.retreated">
              <el-col :span="12">
                <el-card class="box-card">
                  <div slot="header" class="clearfix">
                    <span>未入账费用</span>

                  </div>
                  <el-table v-show="retreatCheckInFeeDetail.noBillFees"
                            :data="retreatCheckInFeeDetail.noBillFees"
                            border
                            style="width: 100%">
                    <el-table-column
                      prop="nursingItemName"
                      label="项目名称"
                      width="180">
                    </el-table-column>
                    <el-table-column
                      prop="executionCost"
                      label="费用（¥）"
                      width="180">
                      <template slot-scope="scope">
                        <span>{{scope.row.executionCost | money}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="recordedTime"
                      label="产生时间">
                    </el-table-column>
                  </el-table>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card class="box-card" v-for="(item, key) in retreatCheckInFeeDetail.billFees" :key="key">
                  <div slot="header" class="clearfix">
                    <span>账单号：{{key}}</span>
                  </div>
                  <el-table v-show="item"
                            :data="item"
                            border
                            style="width: 100%">
                    <el-table-column
                      prop="nursingItemName"
                      label="项目名称"
                      width="180">
                    </el-table-column>
                    <el-table-column
                      prop="executionCost"
                      label="费用（¥）"
                      width="180">
                      <template slot-scope="scope">
                        <span>{{scope.row.executionCost | money}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="recordedTime"
                      label="产生时间">
                    </el-table-column>
                  </el-table>
                </el-card>
              </el-col>
            </el-row>

          </el-tab-pane>
        </el-tabs>
      </el-row>
      <el-dialog title="记账并结算" :visible.sync="wbdialogVisible" width="30%" >
        <span style="font-size: 20px; color: #ff8866; text-align: center;" >总金额(¥)：{{settleBill.amount | money}}</span>
        <el-divider></el-divider>
        <el-form  label-width="80px">
          <el-form-item label="预交金(¥)">
            <el-input type="number"  v-model="settleBill.payinfo.yjj"></el-input>
          </el-form-item>
          <el-form-item label="现金(¥)">
            <el-input type="number"  v-model="settleBill.payinfo.xj"></el-input>
          </el-form-item>
          <el-form-item label="扫码(¥)">
            <el-input type="number"  v-model="settleBill.payinfo.scan"></el-input>
          </el-form-item>
          <el-form-item label="银联(¥)">
            <el-input type="number"  v-model="settleBill.payinfo.union"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="wbdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="writeFeeSettle">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="账单结算" :visible.sync="billdialogVisible" width="30%" >
        <span style="font-size: 20px; color: #ff8866; text-align: center;" >总金额(¥)：{{billSettleInfo.billinfo.amount | money}}</span>
        <el-divider></el-divider>
        <el-form  label-width="80px">
          <el-form-item label="预交金(¥)">
            <el-input type="number" v-model="billSettleInfo.payinfo.yjj"></el-input>
          </el-form-item>
          <el-form-item label="现金(¥)">
            <el-input type="number" v-model="billSettleInfo.payinfo.xj"></el-input>
          </el-form-item>
          <el-form-item label="扫码(¥)">
            <el-input type="number" v-model="billSettleInfo.payinfo.scan"></el-input>
          </el-form-item>
          <el-form-item label="银联(¥)">
            <el-input type="number" v-model="billSettleInfo.payinfo.union"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="billdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="writeBillSettle">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog :title="isMidway ? '中途结算' : '退住结算'" :visible.sync="retreatedialogVisible" width="30%" >
        <span style="font-size: 20px; color: #ff8866; text-align: center;" >总金额(¥)：{{retreateSettleInfo.amount | money}}</span>
        <el-divider></el-divider>
        <el-form  label-width="80px">
          <el-form-item label="预交金(¥)">
            <el-input type="number" v-model="retreateSettleInfo.payinfo.yjj"></el-input>
          </el-form-item>
          <el-form-item label="现金(¥)">
            <el-input type="number" v-model="retreateSettleInfo.payinfo.xj"></el-input>
          </el-form-item>
          <el-form-item label="扫码(¥)">
            <el-input type="number" v-model="retreateSettleInfo.payinfo.scan"></el-input>
          </el-form-item>
          <el-form-item label="银联(¥)">
          <el-input type="number" v-model="retreateSettleInfo.payinfo.union"></el-input>
        </el-form-item>
<!--          <el-form-item label="退住原因">-->
<!--            <el-input type="textarea" v-model="retreateSettleInfo.remark"></el-input>-->
<!--          </el-form-item>-->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="retreatedialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="retreatBill">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="支付方式" :visible.sync="paytypedialogVisible" width="30%" >
        <span style="font-size: 20px; color: #ff8866; text-align: center;" >总金额(¥)：{{revokeSettledInfo.amount | money}}</span>
        <el-divider></el-divider>
        <el-form  label-width="80px">
          <el-form-item label="结算方式">
              <el-select v-model="revokeSettledInfo.payType"  placeholder="请选择结算方式">
                <el-option label="预交金" value="1"></el-option>
                <el-option label="现金" value="2"></el-option>
                <el-option label="扫码" value="3"></el-option>
                <el-option label="银行卡" value="4"></el-option>
              </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="paytypedialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="revokedsettledfeeDetail">确 定</el-button>
        </div>
      </el-dialog>
      <bill_detail_dialog ref="billDetailDialog"></bill_detail_dialog>
    </div>
    <el-dialog title="退押金和预交金" :visible.sync="depositAdvancePaymentVisible" width="30%" >
      <el-form label-width="120px">
        <el-form-item label="预交金(¥)">
          {{ accountInfo.advancePayment | money }}
        </el-form-item>
        <el-form-item label="押金(¥)">
          {{ accountInfo.deposit | money }}
        </el-form-item>
        <el-form-item label="应退合计(¥)">
          {{ (accountInfo.advancePayment + accountInfo.deposit) | money }}
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="depositAdvancePaymentVisible = false">取 消</el-button>
        <el-button type="primary" @click="depositAdvancePaymentSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>

</template>

<script>
  import { searchElderlyFilesOfCondition } from '@/api/elderly'
  import { searchCheckInInfoOfElderly } from '@/api/checkin'
  import { searchAccountDetail, refundAdvancePayment, refundDeposit } from '@/api/account'
  import { searchAllItemInfos } from '@/api/item'
  import { writeFeeToBill } from '@/api/checkinfee'
  import { provisionalSettlement, settleOfMonthBill, settleOfRetreat, settleOfHalfway } from '@/api/settle'
  import { searchBillOfPage, searchBillDetail,generateMonthBill } from '@/api/bill'
  import { searchAllfeeDetailsOfNoBill, revokefeeDetail, searchRetreatCheckInFeeDetail, revokeSettledFeeDetail } from '@/api/checkinfee'
  import BillDetail from './components/BillDetail'
  import { parseTime} from "@/utils/index";
  import searchInput from '@/components/searchInput'
  import Template from "../../nursing/template";
    export default {
        name: "",
        props: {
            checkinmarkrouter: {default: ''}
        },
        components: {
            Template,
            bill_detail_dialog: BillDetail,
            searchInput
        },
        filters: {
            parseTime: parseTime,
            money(val) {
                val = (val + "").replace(/\$|\,/g, "");
                if (isNaN(val)) {
                    val = "0";
                }
                let sign = (val == (val = Math.abs(val)));
                val = Math.floor(val * 100 + 0.50000000001);
                let cents = val % 100;
                val = Math.floor(val / 100).toString();
                if (cents < 10) {
                    cents = "0" + cents;
                }
                for (let i = 0; i < Math.floor((val.length - (1 + i)) / 3); i++) {
                    val = val.substring(0, val.length - (4 * i + 3)) + "," + val.substring(val.length - (4 * i + 3));
                }

                return (((sign) ? "" : "-") + val + "." + cents);
            }
        },
        data() {
            return {
                name:"snapsettle",
                loading:false,
                sConfig: {
                    api: '/sinohis/pension/fee/itemmanager/searchAllItemInfos',
                    method: 'post',
                    postKey: 'mnemonicCodeOrName',
                    label: 'name',
                    value: 'mark',
                    data: {nurseItemBol: null},
                    keys: [
                        {name: '名称', key: 'name'},
                        {name: '价格', key: 'fee'},
                        {
                            name: '状态', switch: [
                                {name: '护理项目', key: 'nurseItemBol', value: true, type: 'success'},
                                {name: '非护理项目', key: 'nurseItemBol', value: false, type: 'warning'},
                            ]
                        },
                        {
                            name: '状态', switch: [
                                {name: '收费', key: 'charged', value: true, type: 'danger'},
                                {name: '免费', key: 'charged', value: false, type: 'success'},
                            ]
                        },
                        {
                            name: '状态', switch: [
                                {name: '可定价', key: 'change', value: true, type: 'success'},
                            ]
                        }

                    ]
                },
                depositAdvancePaymentVisible: false,
                outingbillQuery: {
                    feeType: '1',
                    settled: '0',
                    startTime: '',
                    endTime: ''
                },
                value2:"",
                ashowflag: true,
                checkInList: [],
                checkInMark: undefined,
                settlementReason:{

                },
                reason: '',
                accountInfo: {
                    "accountNumber": undefined,

                    "advancePayment": undefined,
                    "checkInMark": undefined,
                    "checkInType": undefined,
                    "checkedInTime": undefined,
                    "createTime": undefined,
                    "creator": undefined,
                    "del": undefined,
                    "deposit": undefined,
                    "elderlyCode": undefined,
                    "elderlyName": undefined,
                    "id": undefined,
                    "lastUpdateTime": undefined,
                    "lastUpdator": undefined,
                    "retreat": undefined,
                    "checkInBedInfo": undefined,
                    "compartment": undefined,
                    "version": undefined
                },
                feeItems: [],
                snapFee: {
                    item: undefined,
                    price: undefined,
                    change: undefined,
                    iteminfo: undefined
                },
                snapItem: [],
                settleBill: {
                    amount: 0.00,
                    payinfo: {
                        yjj: "",
                        xj: "",
                        scan: "",
                        union: ""
                    }
                },
                wbdialogVisible: false,
                //已出账单
                outedBills: [],
                //未出账单费用明细
                outingBills: [],
                outedbillpage: {
                    curr: 1,
                    limit: 10,
                    total: 0
                },
                dictionary: "",
                billdialogVisible: false,
                billSettleInfo: {
                    billinfo: {
                        amount: undefined,
                        infos: []
                    },
                    payinfo: {
                        yjj: undefined,
                        xj: undefined,
                        scan: undefined,
                        union: undefined
                    }
                },
                retreatCheckInFeeDetail: {
                    billFees: undefined,
                    noBillFees: undefined,
                    amount: undefined,
                    retreated: false
                },
                retreatedialogVisible: false,
                retreateSettleInfo: {
                    amount: undefined,
                    payinfo: {
                        yjj: undefined,
                        xj: undefined,
                        scan: undefined,
                        union: undefined
                    },
                    remark:"",
                    settleReason:"",
                },
                paytypedialogVisible: false,
                revokeSettledInfo: {
                    detailNumber: undefined,
                    amount: undefined,
                    payType: ''
                },
                isMidway: false,
            }
        },
        methods: {
            depositAdvancePaymentSubmit() {
                this.$confirm('确定要退押金和预交金?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if (this.accountInfo.deposit > 0) {
                        refundDeposit({
                            money: this.accountInfo.deposit,
                            accountNumber: this.accountInfo.accountNumber
                        }).then(res => {
                            if (res.code == '200') {
                                if (this.accountInfo.advancePayment) {
                                    refundAdvancePayment({
                                        money: this.accountInfo.advancePayment,
                                        accountNumber: this.accountInfo.accountNumber
                                    }).then(res => {
                                        if (res.code == '200') {
                                            this.$message({
                                                message: '退费成功',
                                                type: 'success'
                                            });
                                            this.searchNoBill()
                                            this.searchAllInfo(this.accountInfo.checkInMark)
                                            this.depositAdvancePaymentVisible = false
                                        }
                                    })
                                } else {
                                    this.searchNoBill()
                                    this.searchAllInfo(this.accountInfo.checkInMark)
                                    this.depositAdvancePaymentVisible = false
                                }
                            }
                        })
                    }
                })
            },
            moneyformat(val) {
                val = (val + "").replace(/\$|\,/g, "");
                if (isNaN(val)) {
                    val = "0.00";
                }
                return Math.round(val * 100) / 100
            },
            showtop() {
                this.ashowflag = !this.ashowflag
            },
            async searchCheckIn(query) {
                console.log(query,new Date());
                this.loading = true;
                this.checkInList = []
                if (query && query != '' && query.length >= 2) {
                    let elderlyRes = await searchElderlyFilesOfCondition(query)
                    if (elderlyRes.code == '200' && elderlyRes.data) {
                        for (let i = 0; i < elderlyRes.data.length; i++) {
                            let checkinRes = await searchCheckInInfoOfElderly(elderlyRes.data[i].elderlyCode)
                            if (checkinRes.code == '200' && checkinRes.data) {
                                for (let j = 0; j < checkinRes.data.length; j++) {
                                    this.checkInList.push({
                                        checkin: checkinRes.data[j],
                                        elderlyinfo: elderlyRes.data[i]
                                    })
                                }

                            }
                            this.loading = false;
                        }
                    } else {
                        this.checkInList = []
                    }

                } else {
                    this.checkInList = []
                }
            },
            //查询选中老人入住详细信息
            async searchAllInfo(val) {
                    this.name="snapsettle"
                if (!val || val == '') {
                    return false
                }
                this.checkInMark = val
                let accountRes = await searchAccountDetail(val)
                if (accountRes.code == '200' && accountRes.data) {
                    this.accountInfo = accountRes.data
                } else {
                    this.$message.error('查询入住信息失败，' + accountRes.msg);
                }
            },
            async searchFeeItem(query) {
                if (query !== '' && query.length >= 2) {
                    let itemRes = await searchAllItemInfos(query, null)
                    if (itemRes.code == '200' && itemRes.data) {
                        this.feeItems = itemRes.data
                    } else {
                        this.feeItems = []
                    }
                } else {
                    this.feeItems = []
                }
            },
            selVal(val) {
                if (val != '') {
                    for (let i = 0; i < this.feeItems.length; i++) {
                        let fitem = this.feeItems[i]
                        if (fitem.mark == val) {
                            if (fitem.charged) {
                                this.snapFee.price = fitem.fee
                            } else {
                                this.snapFee.price = 0.00
                            }
                            this.snapFee.change = fitem.change
                            this.snapFee.iteminfo = fitem

                            break;
                        }
                    }
                }

            },
            selVal1(row) {
                if (row.charged) {
                    this.snapFee.price = row.fee
                } else {
                    this.snapFee.price = 0.00
                }
                this.snapFee.change = row.change
                this.snapFee.iteminfo = row
            },
            itemclear() {
                this.feeItems = []
                this.snapFee = {
                    item: undefined,
                    price: undefined,
                    change: undefined
                }
            },
            addfeeitem() {
                this.snapItem.push({
                    mark: this.snapFee.iteminfo.mark,
                    name: this.snapFee.iteminfo.name,
                    nurseItemBol: this.snapFee.iteminfo.nurseItemBol,
                    fee: this.snapFee.price
                })
            },
            deleteFeeItem(index, rows) {
                rows.splice(index, 1);
            },
            requstreason(val){
                this.searchNoBill(val)
            },
            //记账
            writebill() {
                if (this.accountInfo.checkInMark && this.snapItem.length > 0) {
                    let data = []
                    this.snapItem.forEach((value, index) => {
                        data.push({
                            itemCode: value.mark,
                            execPrice: value.fee
                        })
                    })

                    writeFeeToBill(this.accountInfo.checkInMark, {
                        executionFeeInfoCreators: data
                    }).then(result => {
                        if (result.code == '200') {
                            this.$message({
                                message: '记账操作成功',
                                type: 'success'
                            });
                            this.itemclear()
                            this.snapItem = []
                        } else {
                            this.$message.error('记账操作失败，' + result.msg);
                        }
                    })
                } else {
                    this.$message({
                        message: '入住信息或费用信息缺失',
                        type: 'warning'
                    });
                }
            },
            //记账并结算-开始
            writesettle() {
                this.settleBill.amount = 0
                if (this.accountInfo.checkInMark && this.snapItem.length > 0) {
                    this.snapItem.forEach((value, index) => {
                        this.settleBill.amount += value.fee
                    })
                    //计算金额
                    if (this.accountInfo.advancePayment >= this.settleBill.amount) {
                        this.settleBill.payinfo.yjj = this.settleBill.amount
                    } else {
                        this.settleBill.payinfo.yjj = this.accountInfo.advancePayment
                        this.settleBill.payinfo.xj = this.settleBill.amount - this.accountInfo.advancePayment
                    }
                    this.wbdialogVisible = true
                } else {
                    this.$message({
                        message: '入住信息或费用信息缺失',
                        type: 'warning'
                    });
                }
            },
            writeFeeSettle() {
                if (this.accountInfo.checkInMark && this.snapItem.length > 0) {
                    let snapExpenseBillInfo = {
                        billDetails: [],
                        payInfo: []
                    }
                    this.snapItem.forEach((value, index) => {
                        snapExpenseBillInfo.billDetails.push({
                            itemCode: value.mark,
                            execPrice: value.fee
                        })
                    })
                    if (this.settleBill.payinfo.yjj && this.settleBill.payinfo.yjj >= 0) {
                        snapExpenseBillInfo.payInfo.push({
                            payType: 1,
                            amount: this.settleBill.payinfo.yjj
                        })
                    }
                    if (this.settleBill.payinfo.xj && this.settleBill.payinfo.xj >= 0) {
                        snapExpenseBillInfo.payInfo.push({
                            payType: 2,
                            amount: this.settleBill.payinfo.xj
                        })
                    }
                    if (this.settleBill.payinfo.scan && this.settleBill.payinfo.scan >= 0) {
                        snapExpenseBillInfo.payInfo.push({
                            payType: 3,
                            amount: this.settleBill.payinfo.scan
                        })
                    }
                    if (this.settleBill.payinfo.union && this.settleBill.payinfo.union >= 0) {
                        snapExpenseBillInfo.payInfo.push({
                            payType: 4,
                            amount: this.settleBill.payinfo.union
                        })
                    }
                    provisionalSettlement(this.accountInfo.checkInMark, snapExpenseBillInfo).then(result => {
                        if (result.code == '200') {
                            this.$message({
                                message: '结算操作成功',
                                type: 'success'
                            });
                            this.itemclear()
                            this.snapItem = []
                            this.settleBill = {
                                amount: 0.00,
                                payinfo: {
                                    yjj: undefined,
                                    xj: undefined,
                                    scan: undefined,
                                    union: undefined
                                }
                            }
                            this.wbdialogVisible = false
                        } else {
                            this.$message.error('结算操作失败，' + result.msg);
                        }
                    })
                } else {
                    this.$message({
                        message: '入住信息或费用信息缺失',
                        type: 'warning'
                    });
                }
            },
            //查询已出账单
            searchOutedBills() {
                let params = {
                    currPageNo: this.outedbillpage.curr,
                    limit: this.outedbillpage.limit,
                    settled: null,
                    billDate:this.value2

                }
                searchBillOfPage(this.accountInfo.checkInMark, params).then(result => {
                    if (result.code == '200') {
                        if (result.data.data) {
                            this.outedBills = result.data.data
                            this.outedbillpage.total = result.data.total
                        } else {
                            this.outedBills = []
                            this.outedbillpage.total = 0
                        }
                    } else {
                        this.$message.error('查询已出账单异常，' + result.msg)
                    }
                })
            },
            //生成月份账单
            generateMonthBill(){
                let params = {

                    checkInMark: this.accountInfo.checkInMark,
                    monthDate:this.value2

                }
                generateMonthBill(params).then(result => {
                    console.log(result)
                    this.searchOutedBills()
                })
            },
            //查询未出账单
            searchOutingBills() {
                searchAllfeeDetailsOfNoBill(this.accountInfo.checkInMark, this.outingbillQuery).then(result => {
                    if (result.code == '200') {
                        if (result.data) {
                            this.outingBills = result.data
                        } else {
                            this.outingBills = []
                        }
                    } else {
                        this.$message.error('查询未出账单异常，' + result.msg)
                    }
                })
            },
            tabClick(tab) {
                if (tab.name == 'outedbill') {//已出账单
                    if (this.accountInfo.checkInMark) {
                        this.name='outedbill'
                        var date = new Date();
                        var year = date.getFullYear();
                        var month = date.getMonth();
                        var toMonth = year + "-"+ (month + 1) ;
                        var aa=toMonth

                        var bb=aa.toString();
                        console.log(bb)
                        this.value2 = toMonth;
                        this.searchOutedBills()
                    }
                } else if (tab.name == 'outingbill') {//未出账单
                    if (this.accountInfo.checkInMark) {
                        this.searchOutingBills()
                    }
                } else if (tab.name == 'retreatbill') {//退住结算
                    this.isMidway = false
                    if (this.accountInfo.checkInMark) {
                        this.searchNoBill()
                    }
                } else if (tab.name == 'midwaySettlement') {//中途结算
                    this.isMidway = true
                    if (this.accountInfo.checkInMark) {
                        this.searchNoBill()
                    }
                }
            },
            revokefee(detailSn) {
                this.$confirm('确定要撤销该费用?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    revokefeeDetail(detailSn).then(result => {
                        if (result.code == '200') {
                            this.$message({
                                message: '费用撤销成功',
                                type: 'success'
                            })
                            this.searchOutingBills()
                        } else {
                            this.$message.error('费用撤销失败，' + result.msg);
                        }
                    })
                }).catch(reason => {
                    console.log(reason);
                });
            },
            revokesettledfee(row) {
                this.revokeSettledInfo.detailNumber = row.detailNumber
                this.revokeSettledInfo.amount = row.executionCost
                this.paytypedialogVisible = true
            },
            async revokedsettledfeeDetail() {
                let data = {
                    amount: 0 - this.revokeSettledInfo.amount,
                    payType: this.revokeSettledInfo.payType
                }
                let revokeRes = await revokeSettledFeeDetail(this.revokeSettledInfo.detailNumber, data)
                if (revokeRes.code == '200') {
                    this.$message({
                        message: '撤销成功',
                        type: 'success'
                    });
                } else {
                    this.$message.error('撤销失败,' + revokeRes.msg);
                }
            },
            showBillDetail(row) {
                searchBillDetail(row.billCode).then(result => {
                    if (result.code == '200') {
                        this.$refs["billDetailDialog"].show(result.data);
                    } else {
                        this.$message.error('查询账单详情异常，' + result.msg)
                    }
                })

            },
            settleToBill(row) {

                this.billSettleInfo = {
                    billinfo: {
                        amount: undefined,
                        infos: []
                    },
                    payinfo: {
                        yjj: undefined,
                        xj: undefined,
                        scan: undefined,
                        union: undefined
                    }
                }
                if (this.accountInfo.accountNumber) {
                    this.billSettleInfo.billinfo.infos.push(row)
                    let amount = 0.00
                    this.billSettleInfo.billinfo.infos.forEach((value, index) => {
                        amount += value.billFee
                    })
                    this.billSettleInfo.billinfo.amount = amount
                    if (this.accountInfo.advancePayment >= amount) {
                        this.billSettleInfo.payinfo.yjj = amount
                    } else {
                        this.billSettleInfo.payinfo.yjj = this.accountInfo.advancePayment
                        this.billSettleInfo.payinfo.xj = amount - this.accountInfo.advancePayment
                    }
                    this.billdialogVisible = true
                }
            },
            writeBillSettle() {
                let monthBillSettleInfo = {
                    billCodes: [],
                    payInfos: []
                }
                this.billSettleInfo.billinfo.infos.forEach((value, index) => {
                    monthBillSettleInfo.billCodes.push(value.billCode)
                })
                if (this.billSettleInfo.payinfo.yjj && this.billSettleInfo.payinfo.yjj >= 0) {
                    monthBillSettleInfo.payInfos.push({
                        payType: 1,
                        amount: this.billSettleInfo.payinfo.yjj
                    })
                }
                if (this.billSettleInfo.payinfo.xj && this.billSettleInfo.payinfo.xj >= 0) {
                    monthBillSettleInfo.payInfos.push({
                        payType: 2,
                        amount: this.billSettleInfo.payinfo.xj
                    })
                }
                if (this.billSettleInfo.payinfo.scan && this.billSettleInfo.payinfo.scan >= 0) {
                    monthBillSettleInfo.payInfos.push({
                        payType: 3,
                        amount: this.billSettleInfo.payinfo.scan
                    })
                }
                if (this.billSettleInfo.payinfo.union && this.billSettleInfo.payinfo.union >= 0) {
                    monthBillSettleInfo.payInfos.push({
                        payType: 4,
                        amount: this.billSettleInfo.payinfo.union
                    })
                }
                settleOfMonthBill(monthBillSettleInfo).then(result => {
                    if (result.code == '200') {
                        this.$message({
                            message: '结算操作成功',
                            type: 'success'
                        });
                        this.billdialogVisible = false
                        this.billSettleInfo = {
                            billinfo: {
                                amount: undefined,
                                infos: []
                            },
                            payinfo: {
                                yjj: undefined,
                                xj: undefined,
                                scan: undefined,
                                union: undefined
                            }
                        }
                    } else {
                        this.$message.error('结算操作失败，' + result.msg);
                    }
                })

            },
            //退住结算查询未结算费用
            async searchNoBill(val) {
                console.log(val)
                if(val){
                    this.reason=val
                }else {

                    this.reason=1
                }
                let feeRes = await searchRetreatCheckInFeeDetail(this.accountInfo.checkInMark,this.reason)
                if (feeRes.code == '200') {
                    this.retreatCheckInFeeDetail = feeRes.data
                } else {
                    this.$message.error('查询退住未结算费用失败，' + feeRes.msg);
                }
            },
            openretreate() {
                this.retreateSettleInfo.remark=""
                this.retreateSettleInfo.payinfo.scan=""
                this.retreateSettleInfo.payinfo.union=""
                this.retreateSettleInfo.amount = this.retreatCheckInFeeDetail.amount
                if (this.accountInfo.accountNumber) {
                    if (this.accountInfo.advancePayment >= this.retreatCheckInFeeDetail.amount) {
                        this.retreateSettleInfo.payinfo.yjj = this.moneyformat(this.retreatCheckInFeeDetail.amount)
                    } else {
                        this.retreateSettleInfo.payinfo.yjj = this.moneyformat(this.accountInfo.advancePayment)
                        this.retreateSettleInfo.payinfo.xj = this.moneyformat(this.retreatCheckInFeeDetail.amount - this.accountInfo.advancePayment)
                    }
                    this.retreatedialogVisible = true
                }
            },
            async retreatBill() {
                let retreatData = {
                    amount: this.moneyformat(this.retreateSettleInfo.amount),
                    payInfos: [],
                    remark:this.retreateSettleInfo.remark,
                    settleReason:this.reason,
                }
                if (this.retreateSettleInfo.payinfo.yjj && this.retreateSettleInfo.payinfo.yjj >= 0) {
                    retreatData.payInfos.push({
                        payType: 1,
                        amount: this.retreateSettleInfo.payinfo.yjj
                    })
                }
                if (this.retreateSettleInfo.payinfo.xj && this.retreateSettleInfo.payinfo.xj >= 0) {
                    retreatData.payInfos.push({
                        payType: 2,
                        amount: this.retreateSettleInfo.payinfo.xj
                    })
                }
                if (this.retreateSettleInfo.payinfo.scan && this.retreateSettleInfo.payinfo.scan >= 0) {
                    retreatData.payInfos.push({
                        payType: 3,
                        amount: this.retreateSettleInfo.payinfo.scan
                    })
                }
                if (this.retreateSettleInfo.payinfo.union && this.retreateSettleInfo.payinfo.union >= 0) {
                    retreatData.payInfos.push({
                        payType: 4,
                        amount: this.retreateSettleInfo.payinfo.union
                    })
                }
                if (this.isMidway) {
                     retreatData.remark=undefined
                    retreatData.settleReason=undefined


                    let retreatRes = await settleOfHalfway(this.accountInfo.checkInMark, retreatData)
                    if (retreatRes.code == '200') {
                        this.$message({
                            message: '中途结算成功',
                            type: 'success'
                        });
                        this.retreatedialogVisible = false
                        this.searchNoBill()
                        this.searchAllInfo(this.accountInfo.checkInMark)
                    } else {
                        this.$message.error('退住结算失败，' + feeRes.msg);
                    }
                } else {
                    let retreatRes = await settleOfRetreat(this.accountInfo.checkInMark, retreatData)
                    if (retreatRes.code == '200') {
                        this.$message({
                            message: '退住结算成功',
                            type: 'success'
                        });
                        this.retreatedialogVisible = false
                        // 退住结算按钮
                        this.searchNoBill()
                        this.searchAllInfo(this.accountInfo.checkInMark)
                        if (this.accountInfo.deposit > 0) {
                            this.depositAdvancePaymentVisible = true
                        }
                    } else {
                        this.$message.error('退住结算失败，' + feeRes.msg);
                    }
                }

            }
        },
        mounted() {
            console.log(this.$route.params);
            let cim = this.$route.params.checkinmarkrouter
            console.log(cim);
            if (cim && cim != '' && cim != ':checkinmarkrouter') {
                this.searchAllInfo(cim)
            }

            this.dictionary = JSON.parse(localStorage.getItem("dictionary"))
            for (var i = 0; i < this.dictionary.length; i++) {
                if (this.dictionary[i].mark == "settlementReason") {
                    this.settlementReason=(this.dictionary[i].childs)
                    this.reason = this.dictionary[i].childs[0].dcNo
                    console.log( this.reason)

                }
            }
        }
    }
</script>

<style scoped>
  .box-card >>> .el-input__inner {
    border-top-width: 0px;
    border-left-width: 0px;
    border-right-width: 0px;
    border-bottom-width: 1px;
    /*outline: medium;*/
  }
  .el-row {
    margin-bottom: 20px;
  &:last-child {
     margin-bottom: 0;
   }
  }
</style>
